package main

import (
	"net/http"
	"log"
	"encoding/json"
	"bytes"
	"io"
)

func main() {
	http.HandleFunc("/", test)
	address := ":8082"
	log.Println("server will start ", address)
	log.Fatal(http.ListenAndServe(address, nil))
}

var hclient = http.DefaultClient

//var api_server="api.imiaoke.cn" //test
var api_server="localhost:5200" //prod

//curl "http://0.0.0.0:8082/service/?path=api/v1/product/detail&pid=808515"
//curl "http://0.0.0.0:8082/service/?path=api/v1/shop/product/list&btype=json&index=1&size=2&shopId=32287"
//"http://0.0.0.0:8082/service/service/?path=api/v1/shop/product/list"
//{"index":1,"size":12,"shopId":"32287"}

func test(w http.ResponseWriter, r *http.Request) {

	//w.Header().Set("Cache-Control","max-age="+strconv.Itoa(int(129)))
	//w.Header().Set("expires","Tue, 18 Oct 2016 12:33:00 GMT")
	rawUrl := r.URL.String()
	log.Println("rawurl：", rawUrl)

	params := r.URL.Query()
	pathParam := params.Get("path")
	//json from
	btype := params.Get("btype")
	params.Del("path")
	newUrl :="http://"+api_server+r.URL.Path + "?path=" + pathParam

	var err error
	var bodyReader io.Reader

	if btype=="json" {
		//josn post
		jsonObj := map[string]interface{}{}
		for k, v := range params {
			jsonObj[k] = v[0]
		}
		bs, err1 := json.Marshal(jsonObj)
		err = err1
		if err == nil {
			bodyReader = bytes.NewReader(bs);
			log.Println("newUrl body",string(bs))
		}
	}else {
		bodyReader = bytes.NewReader([]byte(r.URL.RawQuery))
	}

	posttype:="application/json; charset=utf-8"
	if(btype!="json"){
		posttype="application/x-www-form-urlencoded; charset=UTF-8"
	}
	log.Println(newUrl,posttype)

	res, err2 := hclient.Post(newUrl, posttype, bodyReader)
	err = err2
	if err == nil {
		io.Copy(w, res.Body.(io.Reader))
		w.(http.Flusher).Flush()
		return
	}

	if (err != nil) {
		w.WriteHeader(500)
		w.Write([]byte(err.Error()))
	}


	//http://localhost:5200/service/?path=api/v1/product/detail


	//w.(http.ResponseWriter).Write(bs)
	//println("header:",r.Header,"body:",string(bs))
}